package com.ruoyi.coffee.service.impl;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.coffee.domain.Products;
import com.ruoyi.coffee.dto.ShopCartDto;
import com.ruoyi.coffee.mapper.ProductsMapper;
import com.ruoyi.coffee.utils.SecurityUtils;
import com.ruoyi.coffee.vo.ShopCartsVo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.ruoyi.coffee.mapper.ShopCartsMapper;
import com.ruoyi.coffee.domain.ShopCarts;
import com.ruoyi.coffee.service.IShopCartsService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 购物车Service业务层处理
 *
 * @author dxj
 * @date 2025-02-10
 */
@Service
@Slf4j
public class ShopCartsServiceImpl extends ServiceImpl<ShopCartsMapper, ShopCarts> implements IShopCartsService {
    @Resource
    private ShopCartsMapper shopCartsMapper;

    @Resource
    private ProductsMapper productsMapper;

    /**
     * 查询购物车
     *
     * @param id 购物车主键
     * @return 购物车
     */
    @Override
    public ShopCarts selectShopCartsById(Long id) {
        return shopCartsMapper.selectShopCartsById(id);
    }

    /**
     * 查询购物车列表
     *
     * @param shopCarts 购物车
     * @return 购物车
     */
    @Override
    public List<ShopCarts> selectShopCartsList(ShopCarts shopCarts) {
        return shopCartsMapper.selectShopCartsList(shopCarts);
    }

    /**
     * 新增购物车
     *
     * @param shopCarts 购物车
     * @return 结果
     */
    @Override
    public int insertShopCarts(ShopCarts shopCarts) {
        shopCarts.setCreateTime(DateUtils.getNowDate());
        return shopCartsMapper.insert(shopCarts);
    }

    /**
     * 修改购物车
     *
     * @param shopCarts 购物车
     * @return 结果
     */
    @Override
    public int updateShopCarts(ShopCarts shopCarts) {
        shopCarts.setUpdateTime(DateUtils.getNowDate());
        return shopCartsMapper.updateShopCarts(shopCarts);
    }

    /**
     * 批量删除购物车
     *
     * @param ids 需要删除的购物车主键
     * @return 结果
     */
    @Override
    public int deleteShopCartsByIds(Long[] ids) {
        return shopCartsMapper.deleteShopCartsByIds(ids);
    }

    /**
     * 删除购物车信息
     *
     * @param id 购物车主键
     * @return 结果
     */
    @Override
    public int deleteShopCartsById(Long id) {
        return shopCartsMapper.deleteShopCartsById(id);
    }

    /**
     * 获取用户购物车详情列表
     *
     * @return
     */
    @Override
    public AjaxResult getShopList() {
        Long currentUserId = SecurityUtils.getUserId();
        try {
            List<ShopCarts> shopCartsList = getShopCartsList(currentUserId);
            Map<Long, Products> productMap = getProductMap(shopCartsList);
            List<ShopCartsVo> voList = buildShopCartsVoList(shopCartsList, productMap);
            return AjaxResult.success(voList);
        } catch (Exception e) {
            log.error("查询购物车失败: userId={}", currentUserId, e);
            return AjaxResult.error("查询失败，请稍后重试");
        }
    }

    /**
     * 加入购物车
     * @param shopCartDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult saveShopCarts(ShopCartDto shopCartDto) {
        Long currentUserId = SecurityUtils.getUserId();
        try {
            shopCartDto.setUserId(currentUserId);
            ShopCarts shopCarts = new ShopCarts();
            BeanUtils.copyProperties(shopCartDto, shopCarts);
            int result = baseMapper.insert(shopCarts);
            return AjaxResult.success(result);
        } catch (Exception e) {
            log.error("加入购物车失败: userId={}, shopCartDto={}", currentUserId, shopCartDto, e);
            return AjaxResult.error("加入购物车失败，请稍后重试");
        }
    }

    /**
     * 更新购物车
     * @param shopCartDto
     * @return
     */
    @Override
    public AjaxResult updateShopCartsInfo(ShopCartDto shopCartDto) {
        Long currentUserId = SecurityUtils.getUserId();
        try {
            ShopCarts shopCarts = new ShopCarts();
            shopCartDto.setUserId(currentUserId);
            BeanUtils.copyProperties(shopCartDto, shopCarts);
            LambdaQueryWrapper<ShopCarts> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ShopCarts::getUserId, currentUserId)
                    .eq(ShopCarts::getId, shopCartDto.getId());
            int result = baseMapper.update(shopCarts, wrapper);
            return AjaxResult.success(result);
        } catch (Exception e) {
            log.error("更新购物车失败: userId={}, shopCartDto={}", currentUserId, shopCartDto, e);
            return AjaxResult.error("更新购物车失败，请稍后重试");
        }
    }

    /**
     * 清空购物车
     * @param ids
     * @return
     */
    @Override
    public AjaxResult removeAllByIds(Long[] ids) {
        try {
            int result = baseMapper.deleteBatchIds(Arrays.asList(ids));
            return AjaxResult.success(result);
        } catch (Exception e) {
            log.error("清空购物车失败: ids={}", ids, e);
            return AjaxResult.error("清空购物车失败，请稍后重试");
        }
    }

    /**
     * 获取购物车列表
     * @param userId
     * @return
     */
    private List<ShopCarts> getShopCartsList(Long userId) {
        LambdaQueryWrapper<ShopCarts> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(ShopCarts::getId, ShopCarts::getProductId, ShopCarts::getQuantity,ShopCarts::getCoffeeType,ShopCarts::getTemperature)
                .eq(ShopCarts::getUserId, userId);
        return baseMapper.selectList(wrapper);
    }

    /**
     * 通过购物车商品id获取商品信息
     * @param shopCartsList
     * @return
     */
    private Map<Long, Products> getProductMap(List<ShopCarts> shopCartsList) {
        // 获取购物车商品id
        List<Long> productIds = shopCartsList.stream()
                .map(ShopCarts::getProductId)
                .distinct()
                .collect(Collectors.toList());
        if (productIds.isEmpty()) {
            return Collections.emptyMap();
        }

        return productsMapper.selectBatchByProductIds(productIds).stream()
                .collect(Collectors.toMap(Products::getProductId, Function.identity()));
    }

    /**
     * 构造购物车列表信息Vo
     * @param shopCartsList
     * @param productMap
     * @return
     */
    private List<ShopCartsVo> buildShopCartsVoList(List<ShopCarts> shopCartsList, Map<Long, Products> productMap) {
        return shopCartsList.stream()
                .map(shopCart -> {
                    ShopCartsVo vo = new ShopCartsVo();
                    Products product = productMap.get(shopCart.getProductId());
                    if (product != null) {
                        vo.setProductName(product.getProductName());
                        vo.setProductImages(product.getImageUrl());
                        vo.setPrice(product.getPrice().toString());
                    }
                    BeanUtils.copyProperties(shopCart, vo);
                    return vo;
                })
                .collect(Collectors.toList());
    }
}
